﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net  登陆页控制器       ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------

using System;
using System.Web.Mvc;
using Wedn.Net.Common;
using Wedn.Net.Controller.Base;
using Wedn.Net.Model;
using Wedn.Net.Model.View;
using Wedn.Net.OAuth;
using Wedn.Net.OAuth.Context;
using Wedn.Net.Utility;

namespace Wedn.Net.Admin.Controllers
{
    /// <summary>
    /// 登陆页控制器
    /// </summary>
    public class LoginController : FrontBaseController
    {
        /// <summary>
        /// 登陆页
        /// </summary>
        [HttpGet]
        public ActionResult Index(string redirect)
        {
            if (BllInstance.UserManager.CheckLogin())
            {
                //var url = RequestHelper.QueryString("redirect");
                redirect = string.IsNullOrEmpty(redirect) ? "/" : redirect;
                //用户已登陆 //校验Cookie登陆；
                //HttpContext.Response.Redirect(redirect);
                return Redirect(redirect);
            }
            //var loginer = new LoginUser() { Redirect = redirect };
            ViewBag.Title = "登录";
            return View();
        }
        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="loginer"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public JsonResult Index(LoginUser loginer)
        {
            //return Content(string.Format("Hello {0}", loginer.Username));
            if (string.IsNullOrEmpty(loginer.Username) || string.IsNullOrEmpty(loginer.Password))
                Response.End();//用户名密码为空
            User user;
            var loginRes = BllInstance.UserManager.Login(loginer.Username, loginer.Password, out user);
            if (loginRes == LoginResult.Success)
            {
                SessionHelper.AddSession("CurrentUser", user);
                if (loginer.IsChecked)
                    CookieHelper.SetCookie("URM", BllInstance.UserManager.GetEncryptUserInfo(user));
            }
            return Json(new { Result = loginRes.ToString(), Redirect = loginer.Redirect });
        }

        /// <summary> 
        /// QQ登陆页面 
        /// </summary>
        [HttpGet]
        public ActionResult OAuth()
        {
            var context = new QzoneContext();
            var state = Guid.NewGuid().ToString().Replace("-", "");
            SessionHelper.AddSession("requeststate", state, 10);
            const string scope = "get_user_info,add_share,list_album,upload_pic,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idolist,add_idol,del_idol,add_one_blog,add_topic,get_tenpay_addr";
            var authenticationUrl = context.GetAuthorizationUrl(state, scope);
            return new RedirectResult(authenticationUrl);

        }

        /// <summary> 
        /// 回调页面 
        /// </summary>
        [HttpGet]
        public ActionResult Callback()
        {
            var code = RequestHelper.QueryString("code");
            if (string.IsNullOrEmpty(code)) return Redirect(Url.Action("Index", "Login"));

            var state = RequestHelper.QueryString("state");
            var requestState = SessionHelper.GetSession("requeststate");
            if (state != requestState) return Redirect(Url.Action("Index", "Login"));
            var qzone = new QOpenClient(code, state);
            var qzoneUser = qzone.GetCurrentUser();
            //if (SessionHelper.GetSession<QOpenClient>("QzoneOauth") == null)
            //{
            //    SessionHelper.AddSession("QzoneOauth",qzone);
            //}
            var nickname = qzoneUser.Nickname;
            User currentUser;
            if (BLLFactory.BLLFactory.Instance.UserManager.OAuthLogin(nickname, out currentUser) == LoginResult.OAuthFail)
            {
                currentUser = new User
                {
                    Login = nickname.ToLower(),
                    NickName = nickname,
                    Role = (short)UserRole.OAuthUser,
                    Status = (short)UserStatus.Default,
                    RegDate = DateTime.Now,
                    Password = StringHelper.Encrypt(nickname),
                    Link = string.Empty,
                    Email = string.Empty
                };
                if (0 == BllInstance.UserManager.Insert(currentUser, true).Id)
                    //ResponseStr(LoginResult.OAuthFail.ToString());
                    return Redirect(Url.Action("Index", "Login"));
            }
            SessionHelper.AddSession("CurrentUser", currentUser);

            return Redirect(Url.Action("Index", "Blog"));
        }

    }
}
